import React, { useState, useEffect, useRef } from 'react';
import { useNavigate } from 'react-router-dom';
import styles from './Homepage.module.css';

// 产品卡片组件
const ProductCard = ({ product, useBackgroundImage = false }) => (
  <div className={styles.productCard}>
    <div className={styles.productImageContainer}>
      {useBackgroundImage ? (
        <div 
          className={styles.productImage} 
          style={{ 
            backgroundImage: `url(${product.image})`,
            backgroundSize: 'cover',
            backgroundPosition: 'center'
          }} 
        />
      ) : (
        <div className={styles.productImage} style={{ backgroundImage: `url(${product.image})` }} />
      )}
      {product.tag && <div className={styles.productTag}>{product.tag}</div>}
    </div>
    <div className={styles.productInfo}>
      <h3 className={styles.productTitle}>{product.title}</h3>
      <div className={styles.priceContainer}>
        <span className={styles.currentPrice}>¥{product.price}</span>
        {product.originalPrice && (
          <span className={styles.originalPrice}>¥{product.originalPrice}</span>
        )}
      </div>
      <div className={styles.productMeta}>
        <span className={styles.sales}>{product.sales}人已购</span>
        {product.rating && (
          <span className={styles.rating}>
            <span className={styles.ratingStars}>★★★★★</span>
            {product.rating}
          </span>
        )}
      </div>
    </div>
  </div>
);

// 分类标签组件
const CategoryTab = ({ tabs, activeTab, onChange }) => {
  const tabsRef = useRef(null);
  
  useEffect(() => {
    if (tabsRef.current) {
      const activeElement = tabsRef.current.querySelector(`.${styles.tabItem}.${styles.active}`);
      if (activeElement) {
        activeElement.scrollIntoView({
          behavior: 'smooth',
          block: 'nearest',
          inline: 'center'
        });
      }
    }
  }, [activeTab]);

  return (
    <div className={styles.categoryTabs}>
      <div className={styles.tabsContainer} ref={tabsRef}>
        {tabs.map((tab) => (
          <div
            key={tab.id}
            className={`${styles.tabItem} ${activeTab === tab.id ? styles.active : ''}`}
            onClick={() => onChange(tab.id)}
          >
            {tab.name}
            {activeTab === tab.id && <div className={styles.tabIndicator} />}
          </div>
        ))}
      </div>
    </div>
  );
};

// 轮播图组件
const BannerCarousel = () => {
  const banners = [
    {
      id: 1,
      title: '春季新品上市',
      subtitle: '全场低至5折',
      bgColor: 'linear-gradient(135deg, #FF9A9E 0%, #FAD0C4 100%)',
      image: '../public/20.png'
    },
    {
      id: 2,
      title: '限时秒杀',
      subtitle: '每日10点开抢',
      bgColor: 'linear-gradient(135deg, #FFB347 0%, #FFCC33 100%)',
      image: '../public/19.png'
    }
  ];
  
  const [currentBanner, setCurrentBanner] = useState(0);
  
  useEffect(() => {
    const timer = setInterval(() => {
      setCurrentBanner((prev) => (prev + 1) % banners.length);
    }, 5000);
    return () => clearInterval(timer);
  }, []);
  
  return (
    <div className={styles.bannerCarousel}>
      {banners.map((banner, index) => (
        <div
          key={banner.id}
          className={`${styles.bannerSlide} ${index === currentBanner ? styles.active : ''}`}
          style={{ 
            backgroundImage: `url(${banner.image})`,
            backgroundSize: 'cover',
            backgroundColor: banner.bgColor
          }}
        >
          <div className={styles.bannerContent}>
            <div className={styles.bannerText}>
              <h2>{banner.title}</h2>
              <p>{banner.subtitle}</p>
              <button className={styles.bannerButton}>立即查看</button>
            </div>
            <div className={styles.bannerImage}/>
          </div>
        </div>
      ))}
      <div className={styles.bannerDots}>
        {banners.map((_, index) => (
          <div
            key={index}
            className={`${styles.dot} ${index === currentBanner ? styles.active : ''}`}
            onClick={() => setCurrentBanner(index)}
          />
        ))}
      </div>
    </div>
  );
};

// 功能入口组件
const FeatureGrid = () => {
  const features = [
    { id: 1, icon: '🎯', name: '幸运转盘' },
    { id: 2, icon: '💰', name: '优惠券' },
    { id: 3, icon: '👥', name: '拼团' },
    { id: 4, icon: '🎁', name: '积分兑换' },
    { id: 5, icon: '📱', name: '手机充值' },
    { id: 6, icon: '✈️', name: '旅行' },
    { id: 7, icon: '🍎', name: '生鲜' },
    { id: 8, icon: '🛒', name: '全部分类' }
  ];
  
  return (
    <div className={styles.featureGrid}>
      {features.map((feature) => (
        <div key={feature.id} className={styles.featureItem}>
          <div className={styles.featureIcon}>{feature.icon}</div>
          <div className={styles.featureName}>{feature.name}</div>
        </div>
      ))}
    </div>
  );
};

// 限时秒杀组件
const FlashSale = () => {
  const [timeLeft, setTimeLeft] = useState({
    hours: '02',
    minutes: '30',
    seconds: '45'
  });
  
  useEffect(() => {
    const timer = setInterval(() => {
      setTimeLeft(prev => {
        let seconds = parseInt(prev.seconds) - 1;
        let minutes = parseInt(prev.minutes);
        let hours = parseInt(prev.hours);
        
        if (seconds < 0) {
          seconds = 59;
          minutes -= 1;
        }
        if (minutes < 0) {
          minutes = 59;
          hours -= 1;
        }
        if (hours < 0) {
          clearInterval(timer);
          return { hours: '00', minutes: '00', seconds: '00' };
        }
        
        return {
          hours: hours.toString().padStart(2, '0'),
          minutes: minutes.toString().padStart(2, '0'),
          seconds: seconds.toString().padStart(2, '0')
        };
      });
    }, 1000);
    
    return () => clearInterval(timer);
  }, []);
  
  const flashSaleProducts = [
    {
      id: 1,
      title: '高端无线耳机',
      price: '299',
      originalPrice: '499',
      sales: '1250',
      image: '../public/无线耳机.png',
      tag: '秒杀'
    },
    {
      id: 2,
      title: '智能手表',
      price: '399',
      originalPrice: '599',
      sales: '980',
      image: '../public/手表.png',
      tag: '秒杀'
    }
  ];
  
  return (
    <div className={styles.flashSaleSection}>
      <div className={styles.sectionHeader}>
        <div className={styles.sectionTitle}>
          <span className={styles.titleIcon}>⚡</span>
          <span>限时秒杀</span>
        </div>
        <div className={styles.countdown}>
          <span>{timeLeft.hours}</span>:
          <span>{timeLeft.minutes}</span>:
          <span>{timeLeft.seconds}</span>
        </div>
        <div className={styles.viewAll}>查看全部 &gt;</div>
      </div>
      <div className={styles.flashSaleProducts}>
        {flashSaleProducts.map((product) => (
          <ProductCard key={product.id} product={product} />
        ))}
      </div>
    </div>
  );
};

// 烟酒专区内容组件
const SmokeContent = () => {
  const smokeCategories = [
    { id: 'cigarette', name: '香烟',imgage:'../public/香烟.png' },
    { id: 'liquor', name: '白酒',imgage:'../public/白酒.png'  },
    { id: 'wine', name: '红酒' ,imgage:'../public/红酒.png' },
    { id: 'foreign', name: '洋酒' ,imgage:'../public/洋酒.png' },
    { id: 'gift', name: '礼盒' ,imgage:'../public/礼盒.png' },
    { id: 'accessories', name: '配件' ,imgage:'../public/配件.png' }
  ];
  
  const [activeSmokeCategory, setActiveSmokeCategory] = useState('cigarette');
  
  const smokeProducts = [
    {
      id: 1,
      title: '中华香烟礼盒',
      price: '699',
      originalPrice: '899',
      sales: '520',
      rating: '4.8',
      image: '../public/香烟.png',
      tag: '热销'
    },
    {
      id: 2,
      title: '茅台酒',
      price: '2499',
      originalPrice: '2999',
      sales: '380',
      rating: '4.9',
      image: '../public/白酒.png',
      tag: '新品'
    },
    {
      id: 3,
      title: '拉菲红酒',
      price: '899',
      originalPrice: '1299',
      sales: '210',
      rating: '4.7',
      image: '../public/拉菲.jfif'
    },
    {
      id: 4,
      title: '卡比龙总裁香烟',
      price: '599',
      sales: '180',
      rating: '4.6',
      image: '../public/卡比龙总裁烟.png'
    }
  ];

  return (
    <div className={styles.categoryContent}>
      {/* 烟酒分类标签 */}
      <div className={styles.subCategoryTabs}>
        <div className={styles.tabsContainer}>
          {smokeCategories.map((tab) => (
            <div
              key={tab.id}
              className={`${styles.tabItem} ${activeSmokeCategory === tab.id ? styles.active : ''}`}
              onClick={() => setActiveSmokeCategory(tab.id)}
            >
               <img src=  {tab.imgage} alt=""width={"50px"} /><br></br>
              {tab.name}
           <div>
          
           </div>
            </div>
          ))}
        </div>
      </div>
      
      {/* 排行榜区域 */}
      <div className={styles.rankingSection}>
        <div className={styles.sectionHeader}>
          <div className={styles.sectionTitle}>排行榜</div>
          <div className={styles.updateInfo}>每日更新</div>
        </div>
        <div className={styles.productGrid}>
          {smokeProducts.slice(0, 2).map((product) => (
            <ProductCard key={product.id} product={product} useBackgroundImage={true} />
          ))}
        </div>
      </div>
      
      {/* 小编推荐区域 */}
      <div className={styles.recommendSection}
      
      >
        <div className={styles.sectionHeader}>
          <div className={styles.sectionTitle}>小编推荐</div>
          <div className={styles.recommendTag}>精选好货</div>
        </div>
        <div className={styles.productGrid}
          
        >
          {smokeProducts.slice(2, 4).map((product) => (
            <ProductCard key={product.id} product={product}  />
          ))}
        </div>
      </div>
    </div>
  );
};

// 汽车用品内容组件
const CarContent = () => {
  const carCategories = [
    { id: 'exterior', name: '外观装饰' },
    { id: 'interior', name: '内饰用品' },
    { id: 'electronic', name: '车载电器' },
    { id: 'clean', name: '清洁养护' },
    { id: 'safety', name: '安全应急' },
    { id: 'tool', name: '维修工具' }
  ];
  
  const [activeCarCategory, setActiveCarCategory] = useState('exterior');
  
  const carProducts = [
    {
      id: 1,
      title: '车载空气净化器',
      price: '299',
      originalPrice: '399',
      sales: '1250',
      rating: '4.7',
      image: 'https://via.placeholder.com/300x300/EEEEEE/555555?text=车载净化器',
      tag: '热销'
    },
    {
      id: 2,
      title: '汽车坐垫套装',
      price: '199',
      originalPrice: '299',
      sales: '980',
      rating: '4.8',
      image: 'https://via.placeholder.com/300x300/EEEEEE/555555?text=汽车坐垫'
    },
    {
      id: 3,
      title: '车载充电器',
      price: '59',
      sales: '3560',
      rating: '4.6',
      image: 'https://via.placeholder.com/300x300/EEEEEE/555555?text=车载充电器',
      tag: '秒杀'
    },
    {
      id: 4,
      title: '汽车香水',
      price: '89',
      originalPrice: '129',
      sales: '1240',
      rating: '4.5',
      image: 'https://via.placeholder.com/300x300/EEEEEE/555555?text=汽车香水'
    }
  ];

  return (
    <div className={styles.categoryContent}>
      {/* 汽车分类标签 */}
      <div className={styles.subCategoryTabs}>
        <div className={styles.tabsContainer}>
          {carCategories.map((tab) => (
            <div
              key={tab.id}
              className={`${styles.tabItem} ${activeCarCategory === tab.id ? styles.active : ''}`}
              onClick={() => setActiveCarCategory(tab.id)}
            >
              {tab.name}
            </div>
          ))}
        </div>
      </div>
      
      {/* 排行榜区域 */}
      <div className={styles.rankingSection}>
        <div className={styles.sectionHeader}>
          <div className={styles.sectionTitle}>排行榜</div>
          <div className={styles.updateInfo}>每日更新</div>
        </div>
        <div className={styles.productGrid}>
          {carProducts.slice(0, 2).map((product) => (
            <ProductCard key={product.id} product={product} />
          ))}
        </div>
      </div>
      
      {/* 小编推荐区域 */}
      <div className={styles.recommendSection}>
        <div className={styles.sectionHeader}>
          <div className={styles.sectionTitle}>小编推荐</div>
          <div className={styles.recommendTag}>精选好货</div>
        </div>
        <div className={styles.productGrid}>
          {carProducts.slice(2, 4).map((product) => (
            <ProductCard key={product.id} product={product} />
          ))}
        </div>
      </div>
    </div>
  );
};

// 推荐商品内容组件
const RecommendContent = () => {
  const recommendedProducts = [
    {
      id: 1,
      title: '轻薄笔记本电脑',
      price: '4599',
      originalPrice: '5299',
      sales: '2450',
      rating: '4.9',
      image: '../public/电脑.png'
    },
    {
      id: 2,
      title: '无线充电器',
      price: '129',
      originalPrice: '199',
      sales: '3560',
      rating: '4.7',
      image: '../public/无线充电器.png'
    },
    {
      id: 3,
      title: '智能空气净化器',
      price: '899',
      sales: '1200',
      rating: '4.8',
      image: '../public/净化器.png'
    },
    {
      id: 4,
      title: '全自动咖啡机',
      price: '1299',
      originalPrice: '1599',
      sales: '890',
      rating: '4.6',
      image:'../public/咖啡机.png'
    }
  ];

  return (
    <>
      {/* 轮播图 */}
      <BannerCarousel />
      
      {/* 功能入口 */}
      <FeatureGrid />
      
      {/* 限时秒杀 */}
      <FlashSale />
      
      {/* 推荐商品 */}
      <div className={styles.categoryContent}>
        <div className={styles.sectionHeader}>
          <div className={styles.sectionTitle}>推荐商品</div>
          <div className={styles.viewAll}>查看全部 &gt;</div>
        </div>
        <div className={styles.productGrid}>
          {recommendedProducts.map((product) => (
            <ProductCard key={product.id} product={product} />
          ))}
        </div>
      </div>
    </>
  );
};

// 底部导航栏
const BottomNavigation = ({ activeTab, navigate }) => {
  const navItems = [
    { id: 'homepage', icon: '🏠', name: '首页' },
    { id: 'ltian', icon: '👥', name: '好友' },
    { id: 'vipvr', icon: 'VIP', name: '未开通' },
    { id: 'layout', icon: '🎬', name: '视频' },
    { id: 'my', icon: '👤', name: '我的' }
  ];
  
  return (
    <div className={styles.bottomNavigation}>
      {navItems.map((item) => (
        <div
          key={item.id}
          className={`${styles.navItem} ${activeTab === item.id ? styles.active : ''}`}
          onClick={() => navigate(`/${item.id}`)}
        >
          <div className={styles.navIcon}>{item.icon}</div>
          <div className={styles.navText}>{item.name}</div>
          {activeTab === item.id && <div className={styles.navIndicator} />}
        </div>
      ))}
    </div>
  );
};

// 主页组件
const Homepage = () => {
  const navigate = useNavigate();
  const [activeCategory, setActiveCategory] = useState('recommend');
  
  const categories = [
    { id: 'recommend', name: '推荐' },
    { id: 'hot', name: '热门' },
    { id: 'smoake', name: '烟酒' },
    { id: 'car', name: '汽车' },
    { id: 'food', name: '食品' },
    { id: 'home', name: '家居' },
    { id: 'beauty', name: '美妆' },
    { id: 'sports', name: '运动' },
    { id: 'books', name: '图书' },
    { id: 'health', name: '健康' },
    { id: 'travel', name: '旅行' },
  ];
  
  // 渲染当前分类的内容
  const renderCategoryContent = () => {
    switch(activeCategory) {
      case 'smoake':
        return <SmokeContent />;
      case 'car':
        return <CarContent />;
      case 'recommend':
      default:
        return <RecommendContent />;
    }
  };

  return (
    <div className={styles.container}>
      {/* 顶部搜索栏 */}
      <div className={styles.searchBar}>
        <div className={styles.searchInputContainer}>
          <input
            type="text"
            placeholder="搜索商品"
            className={styles.searchInput}
          />
          <button className={styles.searchButton}>搜索</button>
        </div>
      </div>
      
      {/* 主要内容区域 */}
      <div className={styles.mainContent}>
        {/* 分类标签 - 放在最上层 */}
        <CategoryTab 
          tabs={categories} 
          activeTab={activeCategory} 
          onChange={setActiveCategory} 
        />
        
        {/* 分类内容 */}
        {renderCategoryContent()}
      </div>
      
      {/* 底部导航栏 */}
      <BottomNavigation activeTab="home" navigate={navigate} />
    </div>
  );
};

export default Homepage;